<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" :inline="true" @submit.native.prevent>
        <el-form-item label="物流公司">
          <el-select v-model="searchForm.carrier" placeholder="请选择物流公司" clearable>
            <el-option label="黑猫" value="YAMATO" />
            <el-option label="佐川" value="SAGAWA" />
          </el-select>
        </el-form-item>
        <el-form-item label="体积">
          <el-input v-model="searchForm.volume" placeholder="请输入体积(cm³)" clearable />
        </el-form-item>
        <el-form-item label="地区">
          <el-input v-model="searchForm.region" placeholder="请输入地区" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.is_active" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="true" />
            <el-option label="禁用" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleAdd">新增配置</el-button>
          <el-button
            v-if="multipleSelection.length > 0"
            type="danger"
            icon="el-icon-delete"
            @click="handleBatchDelete"
          >
            批量删除
          </el-button>
        </el-form-item>
      </el-form>
      <div v-if="multipleSelection.length > 0" class="selection-info">
        已选择 <span class="selection-count">{{ multipleSelection.length }}</span> 条数据
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        @selection-change="handleSelectionChange"
        class="custom-table"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        />
        <el-table-column prop="id" label="ID" align="center" min-width="80" />
        <el-table-column prop="carrier_display" label="物流公司" align="center" min-width="120" />
        <el-table-column prop="volume" label="体积(cm³)" align="center" min-width="120" />
        <el-table-column prop="region" label="地区" align="center" min-width="150" />
        <el-table-column prop="price" label="运费(日元)" align="center" min-width="120">
          <template slot-scope="scope">
            ¥{{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column prop="is_active" label="状态" align="center" min-width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.is_active ? 'success' : 'danger'">
              {{ scope.row.is_active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" align="center" min-width="180" />
        <el-table-column prop="update_time" label="更新时间" align="center" min-width="180" />
        <el-table-column label="操作" align="center" min-width="200" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        :current-page="pagination.page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.page_size"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination-container"
      />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="物流公司" prop="carrier">
          <el-select v-model="form.carrier" placeholder="请选择物流公司" style="width: 100%">
            <el-option label="黑猫" value="YAMATO" />
            <el-option label="佐川" value="SAGAWA" />
          </el-select>
        </el-form-item>
        <el-form-item label="体积(cm³)" prop="volume">
          <el-input v-model.number="form.volume" placeholder="请输入体积" />
        </el-form-item>
        <el-form-item label="地区" prop="region">
          <el-input v-model="form.region" placeholder="请输入地区" />
        </el-form-item>
        <el-form-item label="运费(日元)" prop="price">
          <el-input v-model.number="form.price" placeholder="请输入运费" />
        </el-form-item>
        <el-form-item label="状态" prop="is_active">
          <el-switch
            v-model="form.is_active"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchFee, createFeeConfig, updateFeeConfig, deleteFeeConfig, batchDeleteFeeConfig } from '@/api/shipping'

export default {
  name: 'ShippingFee',
  data() {
    return {
      loading: false,
      searchForm: {
        carrier: '',
        volume: '',
        region: '',
        is_active: ''
      },
      tableData: [],
      pagination: {
        page: 1,
        page_size: 20,
        total: 0
      },
      dialogVisible: false,
      dialogTitle: '新增运费配置',
      form: {
        id: null,
        carrier: '',
        volume: '',
        region: '',
        price: '',
        is_active: true
      },
      rules: {
        carrier: [
          { required: true, message: '请选择物流公司', trigger: 'change' }
        ],
        volume: [
          { required: true, message: '请输入体积', trigger: 'blur' },
          { type: 'number', min: 1, message: '体积必须大于0', trigger: 'blur' }
        ],
        region: [
          { required: true, message: '请输入地区', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入运费', trigger: 'blur' },
          { type: 'number', min: 0, message: '运费不能小于0', trigger: 'blur' }
        ]
      },
      multipleSelection: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取列表数据
    async getList() {
      this.loading = true
      try {
        const params = {
          page: this.pagination.page,
          page_size: this.pagination.page_size,
          ...this.searchForm
        }
        const res = await fetchFee(params)
        
        // 检查是否有分页信息（新的API格式）
        if (res.count !== undefined) {
          // 新的API格式：直接包含分页信息
          this.tableData = res.results || []
          this.pagination.total = res.count || 0
        } else if (res.code === 200) {
          // 旧的API格式：包含在data中
          this.tableData = res.data.results || []
          this.pagination.total = res.data.count || 0
        } else {
          this.$message.error(res.message || '获取数据失败')
        }
      } catch (error) {
        console.error('获取运费配置列表失败:', error)
        this.$message.error('获取数据失败')
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.page = 1
      this.getList()
    },

    // 重置搜索
    handleReset() {
      this.searchForm = {
        carrier: '',
        volume: '',
        region: '',
        is_active: ''
      }
      this.handleSearch()
    },

    // 新增
    handleAdd() {
      this.dialogTitle = '新增运费配置'
      this.form = {
        id: null,
        carrier: '',
        volume: '',
        region: '',
        price: '',
        is_active: true
      }
      this.dialogVisible = true
    },

    // 编辑
    handleEdit(row) {
      this.dialogTitle = '编辑运费配置'
      this.form = { ...row }
      this.dialogVisible = true
    },

    // 删除
    handleDelete(row) {
      this.$confirm('警告：删除后数据将永久丢失，无法恢复！', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(async () => {
        try {
          const res = await deleteFeeConfig(row.id)
          if (res.code === 200) {
            this.$message.success('删除成功')
            this.getList()
          } else {
            this.$message.error(res.message || '删除失败')
          }
        } catch (error) {
          console.error('删除运费配置失败:', error)
          this.$message.error('删除失败')
        }
      })
    },

    // 批量删除
    handleBatchDelete() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择要删除的数据')
        return
      }
      this.$confirm(`警告：删除后数据将永久丢失，无法恢复！`, '批量删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(async () => {
        try {
          const ids = this.multipleSelection.map(item => item.id)
          const res = await batchDeleteFeeConfig(ids)
          if (res.code === 200) {
            this.$message.success('批量删除成功')
            this.getList()
            this.multipleSelection = [] // 清空选中
          } else {
            this.$message.error(res.message || '批量删除失败')
          }
        } catch (error) {
          console.error('批量删除运费配置失败:', error)
          this.$message.error('批量删除失败')
        }
      })
    },

    // 表格选中变化
    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    // 提交表单
    handleSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            let res
            if (this.form.id) {
              // 更新
              res = await updateFeeConfig(this.form)
            } else {
              // 新增
              res = await createFeeConfig(this.form)
            }
            
            if (res.code === 200) {
              this.$message.success(this.form.id ? '更新成功' : '新增成功')
              this.dialogVisible = false
              this.getList()
            } else {
              this.$message.error(res.message || '操作失败')
            }
          } catch (error) {
            console.error('提交运费配置失败:', error)
            this.$message.error('操作失败')
          }
        }
      })
    },

    // 对话框关闭
    handleDialogClose() {
      this.$refs.form.resetFields()
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.pagination.page_size = val
      this.getList()
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.pagination.page = val
      this.getList()
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/dialog-common.scss';
@import '@/styles/shipping-common.scss';

.app-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  
  .el-pagination {
    margin-top: 20px;
    text-align: right;
  }
}

.dialog-footer {
  text-align: right;
}

/* 选择信息样式 */
.selection-info {
  height: 32px;
  line-height: 32px;
  font-size: 14px;
  color: #606266;
  background: #f0f9eb;
  padding: 0 12px;
  border-radius: 4px;
  display: inline-flex;
  align-items: center;
  transition: all 0.3s;
  margin-top: 10px;

  .selection-count {
    color: #67c23a;
    font-weight: bold;
    margin: 0 4px;
  }
}

/* 自定义表格样式 */
.custom-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;

  /* 表头样式 */
  ::v-deep .el-table__header-wrapper {
    background-color: #f5f7fa;
  }

  ::v-deep .el-table__header th {
    background-color: #f5f7fa;
    color: #606266;
    font-weight: 600;
    height: 50px;
    padding: 8px 0;
  }

  /* 表格主体样式 */
  ::v-deep .el-table__body td {
    padding: 12px 0;
  }

  /* 移除边框 */
  ::v-deep .el-table--border,
  ::v-deep .el-table--group {
    border: none;
  }

  ::v-deep .el-table--border::after,
  ::v-deep .el-table--group::after {
    display: none;
  }

  ::v-deep .el-table__fixed-right::before,
  ::v-deep .el-table__fixed::before {
    display: none;
  }

  /* 悬停效果 */
  ::v-deep .el-table--enable-row-hover .el-table__body tr:hover > td {
    background-color: #f5f7fa;
  }

  /* 复选框样式 */
  ::v-deep .el-checkbox__inner {
    border-radius: 4px;
    transition: all 0.3s;
  }

  ::v-deep .el-checkbox__input.is-checked .el-checkbox__inner {
    background-color: #67c23a;
    border-color: #67c23a;
  }
}

/* 分页器样式 */
.pagination-container {
  padding: 20px 0;
  text-align: right;
}

/* 按钮通用样式 */
.el-button {
  border-radius: 4px;
  transition: all 0.3s;

  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
}

/* 对话框样式 */
.el-dialog {
  border-radius: 8px;

  .el-dialog__body {
    padding: 20px;
  }

  .el-form-item {
    margin-bottom: 20px;
  }

  .el-form-item__label {
    font-weight: 500;
  }

  .dialog-footer {
    text-align: right;
    padding-top: 10px;
  }
}
</style>

